package com.forever7776.life.web.config.websocket;

import com.alibaba.fastjson.JSONObject;
import com.forever7776.life.core.common.vo.TweetSendVO;
import com.forever7776.life.core.entity.Tweets;
import com.forever7776.life.core.entity.sys.SysUser;
import com.forever7776.life.core.service.ITweetsService;
import com.forever7776.life.core.service.sys.ISysUserService;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;
import util.RelativeDateFormatUtil;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 客户端
 *
 * @author kz
 * @date 2018/03/28
 */
public class InteractiveScreenHandler extends TextWebSocketHandler {


    private final static Logger logger = LoggerFactory.getLogger(InteractiveScreenHandler.class);

    @Autowired
    private ITweetsService iTweetsService;
    @Autowired
    private ISysUserService iSysUserService;

    /**
     * 客户端连接完成之后
     *
     * @param session
     * @throws Exception
     */
    @Override
    public void afterConnectionEstablished(WebSocketSession session)
            throws Exception {
        logger.info("==> conn sessionId={} address={}", session.getId(), session.getLocalAddress().toString());
        String channelName = getChannelFromSession(session);
        WebSocketChannel.addScreenChannel(channelName, session);
        JSONObject eventMessage = new JSONObject();

        /*eventMessage.put("msg", "连接成功");*/
        TextMessage returnMessage = new TextMessage(eventMessage.toJSONString());
        if (session.isOpen()) {
            session.sendMessage(returnMessage);
        }
        logger.info("==> channel={} sessionId={} connected, current screen {} online", channelName, session.getId(), WebSocketChannel.screenSize(channelName));
    }

    /**
     * 接收消息处理
     *
     * @param session
     * @param message
     * @throws Exception
     */
    @Override
    public void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        logger.info("==> sessionId={} message={}", session.getId(), message.getPayload());
        super.handleTextMessage(session, message);
        TextMessage returnMessage = new TextMessage(message.getPayload() + " received at server");
        session.sendMessage(returnMessage);
    }

    /**
     * 异常处理
     *
     * @param session
     * @param exception
     * @throws Exception
     */
    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        super.handleTransportError(session, exception);
    }

    /**
     * 连接终断
     *
     * @param session
     * @param status
     * @throws Exception
     */
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        String channelName = getChannelFromSession(session);
        WebSocketChannel.delScreeChannel(channelName, session);
        logger.info("==> channel={},sessionId={} closed,current screen {} online", channelName, session.getId(), WebSocketChannel.screenSize(channelName));
        super.afterConnectionClosed(session, status);
    }

    private String getChannelFromSession(WebSocketSession session) {
        String channelName = (String) session.getAttributes().get("t");

        return channelName;
    }
}
